package com.jgdt.demo.widget;
import android.text.TextUtils;
import com.librariy.json.JsonArray;
import com.librariy.json.JsonObject;
import com.librariy.net.HttpClient;
import com.librariy.net.HttpRequest;
import com.librariy.util.UIHelper;
import com.jgdt.demo.api.JsonResponse;

import java.util.ArrayList;
import java.util.List;
public abstract class PageListAdapter extends JsonListAdapter{
    public PageListAdapter() {
        super();
    }
    public abstract HttpRequest getRequest(final int position, final int pageNum, final int pageSize);
    protected void loadData(final int position, final int pageNum, final int pageSize) {
        final HttpRequest request = getRequest(position, pageNum, pageSize);
        if (request == null){
            dispatchLoadSuccess(position,null,0);
            return;
        }
        HttpClient.request(request, new JsonResponse() {
            @Override
            public void onCompleted(boolean success, int code, String message, JsonObject originObject) {
                if(!success){
                    UIHelper.showToast(getContext(), TextUtils.isEmpty(message)?"加载数据失败！":message);
                    dispatchLoadSuccess(0, new ArrayList<JsonObject>(), 0);
                    return;
                }
                JsonArray records=originObject.optJsonObject(ResponseKey.data,new JsonObject()).optJsonArray("records",new JsonArray());
                List<JsonObject> retList = convert(records);
                dispatchLoadSuccess(position, retList, retList.size() >= pageSize?1:0);
                return;
            }
        });
    }
}